package com.test.ml.yqs.service;

import com.test.ml.yqs.entity.BetCode;
import com.test.ml.yqs.entity.FenxiResult;
import com.test.ml.yqs.entity.JfPlanEntity;
import com.test.ml.yqs.entity.SystemVariable;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 疾风计划大小升级投注方案
 * 
 * @author 马亮
 *
 */
@Service
public class JfplanBetService {

	private static Logger logger = Logger.getLogger(JfplanBetService.class);

	@Autowired
	private RestTemplate restutil;

	@Value("${plan.chdx.rul}")
	private String lcyxPlanUrl;

	private static String betpid = null;
	private static String betdaxiao = null;
	private static int upmoney = 0;

	private static double totalMoney = 0;
	
	private static double bigLoseMoney=0;
	
	private static double bigWinMoney=0;

	@Autowired
	private CqsscBetService betService;

	/**
	 * 获取计划
	 */
	public List<JfPlanEntity> getPlan() {

		String planResult = restutil.getForObject(lcyxPlanUrl, String.class, "");

		List<JfPlanEntity> plans = getresult(planResult);
		// for (int i = 0; i < plans.size(); i++) {
		// System.out.println(plans.get(i).toString());
		// }

		return plans;

	}

	private List<JfPlanEntity> getresult(String planResult) {
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(planResult);
		planResult = m.replaceAll("");
		List<JfPlanEntity> list = new ArrayList<JfPlanEntity>();
		planResult = planResult.substring(planResult.indexOf("<divclass=\"sub-box1\"id=\"content\">"));

		int flag = 10;

		while (flag > 0) {
			try {
				String str = planResult.substring(planResult.indexOf("<p>") + 3, planResult.indexOf("</p>"));
				if (str != null && str.length() > 0) {
					JfPlanEntity entity = createEntity(str);
					list.add(entity);
					planResult = planResult.substring(planResult.indexOf("</p>") + 4);
				} else {

				}
				flag--;
			} catch (Exception e) {
				e.printStackTrace();
					return null;
			}
		}
		return list;
	}

	private JfPlanEntity createEntity(String str) {
		JfPlanEntity en = new JfPlanEntity();
		en.setPlanStartperiod(Integer.parseInt(str.substring(0, 3)));
		en.setPlanEndperiod(Integer.parseInt(str.substring(4, 7)));
		en.setPlanStr(str.substring(32, 37));
		if (!en.getPlanStr().equals("01234") && !en.getPlanStr().equals("56789")) {
			en.setPlanStr(str.substring(46, 51));
			en.setPlanTime(Integer.parseInt(str.substring(75, 76)));
			en.setPlanResult("计划中");
			en.setTheperiod(en.getPlanStartperiod() + en.getPlanTime() - 1);
		} else {
			en.setTheperiod(Integer.parseInt(str.substring(49, 52)));
			en.setPlanTime(en.getTheperiod() - en.getPlanStartperiod() + 1);
			en.setPlanResult(str.substring(59, 60));
		}

		// <p>023-025┊万┊<font color="#f00">&lt;<span
		// id="tzh">56789</span>&gt;</font>┊正在进行第2期┊……</p>

		return en;
	}

	public static void main(String[] args) {
		// String str =
		// "023-025┊万┊<fontcolor=\"#f00\">&lt;<spanid=\"tzh\">56789</span>&gt;</font>┊正在进行第2期┊……</p>";
		// System.out.println(Integer.parseInt(str.substring(0, 3)));
		// System.out.println(Integer.parseInt(str.substring(4, 7)));
		// System.out.println(str.substring(46, 51));
		// System.out.println(str.substring(75, 76));
		// System.out.println(Integer.parseInt(str.substring(49, 52)));
		// System.out.println(str.substring(59, 60));

		String str = "20171016-100";

		Integer num = Integer.parseInt(str.substring(9));

		System.out.println(num);
		System.out.println(num == 100);

	}

	/**
	 * 分析计划
	 * 
	 * @return
	 */
	public FenxiResult fenxiPlan(List<JfPlanEntity> plans) {
		if(plans==null || plans.size()<10){
			return null;
		}
		if (plans.get(8).getPlanResult().equals("挂")) {
			return null;
		} else if (plans.get(7).getPlanResult().equals("挂")) {
			return createNomalResult(plans.get(9),5);
		} 
		else if (plans.get(6).getPlanResult().equals("挂")) {
			return createNomalResult(plans.get(9),4);
		} else if (plans.get(5).getPlanResult().equals("挂")) {
			return createNomalResult(plans.get(9),3);
		}
		else if (plans.get(4).getPlanResult().equals("挂")) {
			return createNomalResult(plans.get(9),2);
		}
		else{
			return createNomalResult(plans.get(9),1);
		}
	}

	/**
	 * 普通投注
	 * 
	 * @param jfPlanEntity
	 * @return
	 */
	private FenxiResult createNomalResult(JfPlanEntity jfPlanEntity,int fanb) {
		FenxiResult result = new FenxiResult();
		result.setBetCode(jfPlanEntity.getPlanStr().equals("01234") ? BetCode.Q1_MIN : BetCode.Q1_MAX);
		int num = jfPlanEntity.getPlanTime();
		if (num == 1) {
			result.setBetNum(1*fanb);
		} else if (num == 2) {
			result.setBetNum(3*fanb);
		}
		else if (num == 3) {
			result.setBetNum(6*fanb);
		}
		else {
			return null;
		}
		result.setBetPeriod(jfPlanEntity.getTheperiod());
		return result;
	}

	/**
	 * 高概率投注
	 * 
	 * @param jfPlanEntity
	 * @return
	 */
	private FenxiResult createHighResult(JfPlanEntity jfPlanEntity) {
		FenxiResult result = new FenxiResult();
		result.setBetCode(jfPlanEntity.getPlanStr().equals("01234") ? BetCode.Q1_MIN : BetCode.Q1_MAX);
		int num = jfPlanEntity.getPlanTime();
		if (num == 1) {
			result.setBetNum(2);
		} else if (num == 2) {
			result.setBetNum(4);
		} else if (num == 3) {
			result.setBetNum(8);
		} else {
			return null;
		}
		result.setBetPeriod(jfPlanEntity.getTheperiod());
		return result;
	}

	/**
	 * 开始投注
	 */
	public boolean startBet(int money) {
		boolean result = true;
		if (betpid == null || betpid != SystemVariable.pid) {
			List<JfPlanEntity> plans = getPlan();// 获取计划
			FenxiResult res = fenxiPlan(plans);// 分析计划
			 boolean flag=checkPerioud(plans.get(9));
			// 如果分析结果不为空，则可以投注
			if (res != null && flag) {
				if (betpid != null) {
					if (Integer.parseInt(betpid.substring(9)) == (res.getBetPeriod())) {
						return false;// 如果这期和上期拿到是一样的那么这次已经投过了
					}
				}
				result = betService.postbet(res.getBetCode(), res.getBetNum() * money + "");
				if (result) {
					printLog();
					upmoney = res.getBetNum() * money;
					betdaxiao = res.getBetCode().equals(BetCode.Q1_MAX) ? "大" : "小";
					logger.info(res.getBetPeriod() + "period,bet: " + res.getBetNum() * money + " " + res.getBetCode());
					betpid = SystemVariable.pid;
					logger.info("total win money : " + totalMoney);
					if(totalMoney<bigLoseMoney){
						bigLoseMoney=totalMoney;
					}
					if(totalMoney>bigWinMoney){
						bigWinMoney=totalMoney;
					}
					logger.info("big win money : " + bigWinMoney+" ! big lose money : "+bigLoseMoney);
				}
			} else {
				// logger.info("风险期中。。。。不投这期");
				logger.info("this is bad bet ,can not do it now");
			}
			logger.info("================================================");
		}
		return result;
	}
	/**
	 * 判断计划是否与开奖期数一致
	 * @param jfPlanEntity
	 * @return
	 */
	private boolean checkPerioud(JfPlanEntity jfPlanEntity) {
		int pid=Integer.parseInt(SystemVariable.pid.substring(SystemVariable.pid.length()-3));
		//在计划期内
		if(pid>=jfPlanEntity.getPlanStartperiod() && pid<=jfPlanEntity.getPlanEndperiod()){
			return true;
		}
		logger.info("开奖期数与预期期数不相同，有可能计划停更了");
		return false;
	}

	private void printLog() {
		try {
			int code_1 = Integer.parseInt(SystemVariable.upopcode.substring(0, 1));
			String opencode1_dx = code_1 >= 5 ? "大" : "小";
			if (betdaxiao != null) {
				if (betpid.substring(9).equals(SystemVariable.uppid.substring(6))&& opencode1_dx.equals(betdaxiao)) {
					logger.info(betpid + " win " + upmoney);
					totalMoney = totalMoney + upmoney * 0.993;
				} else {
					logger.info(betpid + " lose " + upmoney);
					totalMoney = totalMoney - upmoney;
				}
			}
		} catch (Exception e) {

		}

	}
}
